package com.jsrana.idea.plugin.ideaweather.util;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.IOException;

/**
 * Created by jrana on 7/29/14.
 */
public class HttpUtil {
    public static String getText( String url )
            throws Exception {
        String response = "";
        HttpClient httpClient = new HttpClient();
        HttpMethod method = new GetMethod( url );
        method.getParams().setParameter( HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler( 3, false ) );
        try {
            // Execute the method.
            int statusCode = httpClient.executeMethod( method );

            if ( statusCode != HttpStatus.SC_OK ) {
                System.err.println( "Method failed: " + method.getStatusLine() );
            }

            response = method.getResponseBodyAsString();
        }
        catch ( HttpException e ) {
            System.err.println( "Fatal protocol violation: " + e.getMessage() );
            e.printStackTrace();
        }
        catch ( IOException e ) {
            System.err.println( "Fatal transport error: " + e.getMessage() );
            e.printStackTrace();
        }
        finally {
            // Release the connection.
            method.releaseConnection();
        }

        return response;
    }
}
